import csv

def main():
    # 生成用于储存数据的CSV文件和表头
    with open('data.csv', mode='w', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(['Gender', 'Age', 'Height', 'Weight', 'BMR'])

    while True:
        # 进入主菜单
        choice = menu()
        # 如果选择退出，则结束程序
        if choice == '0':
            print('Bye!')
            break
        # 如果选择计算，则进入计算功能
        elif choice == '1':
            count()

def menu():
    while True:
        print('\n==== BMR Calculator ====')
        print('1. 开始')
        print('0. 退出')
        choice = input('请输入您的选择（1 开始/0 退出）: ')
        # 如果输入不合法，提示重新输入
        if choice not in ['1', '0']:
            print('输入错误，请重新输入1或0！')
            continue
        else:
            return choice

def count():
    try:
        gender = input('您的性别(M/F): ')
        if gender not in ['M', 'F']:
            raise ValueError('性别输入错误，请输入M或F')
            return gender
        age = int(input('您的年龄: '))
        height = float(input('您的身高 (cm): '))
        weight = float(input('您的体重 (kg): '))

        # 根据性别、年龄、身高、体重计算BMR指数
        if gender == 'M':
            bmr = 88.362 + (13.397 * weight) + (4.799 * height) - (5.677 * age)
        elif gender == 'F':
            bmr = 447.593 + (9.247 * weight) + (3.098 * height) - (4.330 * age)
        print('您的BMR指数为：', bmr)
    except ValueError as e:
        print('输入错误，请重新输入！', e)
        return

    # 输出BMR指数并将数据写入CSV文件
    print('BMR: {:.2f}'.format(bmr))
    with open('data.csv', mode='a', newline='') as f:
        writer = csv.writer(f)
        writer.writerow([gender, age, height, weight, bmr])

    # 询问是否继续程序
    while True:
        answer = input('是否继续运行程序 (Y/N)? ')
        if answer.upper() == 'Y':
            break
        elif answer.upper() == 'N':
            return
        else:
            print('输入错误，请重新输入！')
            continue

if __name__ == '__main__':
    main()
